package common.web.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.Region;
import common.util.JSONUtils;
import common.web.vo.Result;

@Controller
@RequestMapping("/system/region")
public class RegionAction extends CommonAction {

	private static final Logger logger = Logger.getLogger(RegionAction.class);

	@RequestMapping("/view/{id}")
	@ResponseBody
	public Result view(@PathVariable String id) {
		Region region = this.baseService.get(Region.class, id);
		if (null == region) {
			return Result.fail("区域不存在");
		}
		Result result = Result.createResult(region);
		// 查询关联的权限
		return result;
	}

	@RequestMapping("/list")
	@ResponseBody
	public Result list(@RequestBody(required = false) JSONObject json) {
		String parentId = json.getString("parentId");
		String sql = null;
		ArrayList<Object> params = new ArrayList<>();
		if (StringUtils.isNotBlank(parentId)) {
			sql = "from Region where parentId = ? order by sort";
			params.add(parentId);
		} else {
			sql = "from Region where parentId is null order by sort";
		}
		return Result.createResult(baseService.find(sql, params.toArray()));
	}

	@RequestMapping("/listAll")
	@ResponseBody
	public Result listAll() {
		String sql = "from Region order by sort";
		return Result.createResult(baseService.find(sql));
	}

	@RequestMapping("/{editType}")
	@ResponseBody
	public Result save(@PathVariable String editType, @RequestBody JSONObject json) {
		Region region = JSONUtils.toJavaObject(json.getJSONObject("entity"), Region.class);
		if (null != region) {
			WebLog log = new WebLog(LogModule.REGION, LogType.ADD, "操作失败");
			if ("update".equals(editType)) {
				log.setType(LogType.UPDATE);
			}
			try {

				// 删除关联部分
				if ("update".equals(editType)) {
					// baseService.dbOperation(grs.toArray(), new Object[] {
					// group }, deletes.toArray());
					super.setCommonUpdateInfo(region);
					baseService.update(region);
					log.setSuccess(MessageFormat.format("修改区域[{0}]成功!", region.getName()));
				} else if ("add".equals(editType)) {
					super.setCommonSaveInfo(region);
					baseService.save(region);
					log.setSuccess(MessageFormat.format("新增区域[{0}]成功!", region.getName()));
				}
			} catch (Exception e) {
				log.setFail(MessageFormat.format("操作区域[{0}]失败!", region.getName()));
				logger.error("", e);
				return Result.fail("数据错误，请刷新后重试");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}

	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Result delete(@PathVariable String id) {
		Region load = baseService.get(Region.class, id);
		if (null != load) {
			WebLog log = new WebLog(LogModule.REGION, LogType.DELETE, "操作失败");
			try {
				String hql = "from Region where parentId = ?";
				List<Object> find = baseService.find(hql, load.getId());
				if (null != find && find.size() > 0) {
					String msg = MessageFormat.format("[{0}]存在关联的子区域,不能删除区域!", load.getName());
					log.setFail(msg);
					return Result.fail(msg);
				}

				super.baseService.delete(load);
				// 日志
				log.setSuccess(MessageFormat.format("删除区域[{0}]成功!", load.getName()));
			} catch (Exception e) {
				log.setFail(MessageFormat.format("删除区域[{0}]失败!", load.getName()));
				logger.error("", e);

				return Result.fail("删除失败");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("区域不存在");
		}
		return Result.SUCCESS;
	}
}
